package com.taotao.sso.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.taoato.sso.service.UserRegisterService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbUserMapper;
import com.taotao.pojo.TbUser;
import com.taotao.pojo.TbUserExample;
import com.taotao.pojo.TbUserExample.Criteria;

@Service
public class UserRegisterServiceImpl implements UserRegisterService {

	// 注入TbUserMapper
	@Autowired
	private TbUserMapper userMapper;

	@Override
	public TaotaoResult checkData(String param, Integer type) {
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		if (type == 1) {
			// username
			if (StringUtils.isEmpty(param.trim())) {
				return TaotaoResult.build(400, "用户名不能为空！", false);
			}
			criteria.andUsernameEqualTo(param);
		} else if (type == 2) {
			// phone
			criteria.andPhoneEqualTo(param);
		} else if (type == 3) {
			// email
			criteria.andEmailEqualTo(param);
		} else {
			// 数据是非法的
			return TaotaoResult.ok(false);
		}

		List<TbUser> users = userMapper.selectByExample(example);
		// 如果查询到了数据证明此数据已存在，不可用
		if (null != users && users.size() > 0) {
			return TaotaoResult.ok(false);
		}

		return TaotaoResult.ok(true);
	}

	@Override
	public TaotaoResult register(TbUser user) {
		if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword().trim())) {
			return TaotaoResult.build(400, "用户名或密码不能为空！");
		}
		// 判断用户名有没有被注册
		TaotaoResult result = checkData(user.getUsername(), 1);
		if (!(boolean) result.getData()) {
			return TaotaoResult.build(400, "用户名已存在！");
		}
		// 判断电话号码有没有被注册
		TaotaoResult result2 = checkData(user.getPhone(), 2);
		if (!(boolean) result2.getData()) {
			return TaotaoResult.build(400, "号码已被其他用户绑定！");
		}
		// 判断邮箱有没有被注册
		TaotaoResult result3 = checkData(user.getEmail(), 3);
		if (!(boolean) result3.getData()) {
			return TaotaoResult.build(400, "邮箱已被其他用户绑定！");
		}
		//补全其他数据，密码MD5加密
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
		user.setPassword(md5Password);
		//插入
		userMapper.insertSelective(user);

		return TaotaoResult.ok();
	}

}
